<?php


function GenerateRandomPassword($chars) {
srand((double) microtime() * 1000000);
      $allowchars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789';

while(++$n < ($chars+1)) $freturn .= $allowchars[rand(0, strlen($allowchars)-1)];

return $freturn;

}

function server_parse($socket, $response, $line = __LINE__)
{
	while (substr($server_response, 3, 1) != ' ')
	{
		if (!($server_response = fgets($socket, 256)))
		{
			echo "Couldn't get mail server response codes";
		}
	}

	if (!(substr($server_response, 0, 3) == $response))
	{
		echo "Ran into problems sending Mail. Response: $server_response";
	}
}

// Replacement or substitute for PHP's mail command
function smtpmail($mail_to, $subject, $message, $headers = '')
{
	global $smtp_host,$smtp_username,$smtp_password;

	// Fix any bare linefeeds in the message to make it RFC821 Compliant.
	$message = preg_replace("#(?<!\r)\n#si", "\r\n", $message);

	if ($headers != '')
	{
		if (is_array($headers))
		{
			if (sizeof($headers) > 1)
			{
				$headers = join("\n", $headers);
			}
			else
			{
				$headers = $headers[0];
			}
		}
		$headers = chop($headers);

		// Make sure there are no bare linefeeds in the headers
		$headers = preg_replace('#(?<!\r)\n#si', "\r\n", $headers);

		// Ok this is rather confusing all things considered,
		// but we have to grab bcc and cc headers and treat them differently
		// Something we really didn't take into consideration originally
		$header_array = explode("\r\n", $headers);
		@reset($header_array);

		$headers = '';
		while(list(, $header) = each($header_array))
		{
			if (preg_match('#^cc:#si', $header))
			{
				$cc = preg_replace('#^cc:(.*)#si', '\1', $header);
			}
			else if (preg_match('#^bcc:#si', $header))
			{
				$bcc = preg_replace('#^bcc:(.*)#si', '\1', $header);
				$header = '';
			}
			$headers .= ($header != '') ? $header . "\r\n" : '';
		}

		$headers = chop($headers);
		$cc = explode(', ', $cc);
		$bcc = explode(', ', $bcc);
	}


	// Ok we have error checked as much as we can to this point let's get on
	// it already.
	if( !$socket = fsockopen($smtp_host, 25, $errno, $errstr, 20) )
	{

	}

	// Wait for reply
	server_parse($socket, "220", __LINE__);

	// Do we want to use AUTH?, send RFC2554 EHLO, else send RFC821 HELO
	// This improved as provided by SirSir to accomodate
	if( !empty($smtp_username) && !empty($smtp_password) )
	{
		fputs($socket, "EHLO " . $smtp_host . "\r\n");
		server_parse($socket, "250", __LINE__);

		fputs($socket, "AUTH LOGIN\r\n");
		server_parse($socket, "334", __LINE__);

		fputs($socket, base64_encode($smtp_username) . "\r\n");
		server_parse($socket, "334", __LINE__);

		fputs($socket, base64_encode($smtp_password) . "\r\n");
		server_parse($socket, "235", __LINE__);
	}
	else
	{
		fputs($socket, "HELO " . $smtp_host . "\r\n");
		server_parse($socket, "250", __LINE__);
	}

	// From this point onward most server response codes should be 250
	// Specify who the mail is from....
	fputs($socket, "MAIL FROM: <adw@gennadich.com>\r\n");
	server_parse($socket, "250", __LINE__);

	// Specify each user to send to and build to header.
	$to_header = '';

	// Add an additional bit of error checking to the To field.
	$mail_to = (trim($mail_to) == '') ? 'Undisclosed-recipients:;' : trim($mail_to);
	if (preg_match('#[^ ]+\@[^ ]+#', $mail_to))
	{
		fputs($socket, "RCPT TO: <$mail_to>\r\n");
		server_parse($socket, "250", __LINE__);
	}

	// Ok now do the CC and BCC fields...
	@reset($bcc);
	while(list(, $bcc_address) = each($bcc))
	{
		// Add an additional bit of error checking to bcc header...
		$bcc_address = trim($bcc_address);
		if (preg_match('#[^ ]+\@[^ ]+#', $bcc_address))
		{
			fputs($socket, "RCPT TO: <$bcc_address>\r\n");
			server_parse($socket, "250", __LINE__);
		}
	}

	@reset($cc);
	while(list(, $cc_address) = each($cc))
	{
		// Add an additional bit of error checking to cc header
		$cc_address = trim($cc_address);
		if (preg_match('#[^ ]+\@[^ ]+#', $cc_address))
		{
			fputs($socket, "RCPT TO: <$cc_address>\r\n");
			server_parse($socket, "250", __LINE__);
		}
	}

	// Ok now we tell the server we are ready to start sending data
	fputs($socket, "DATA\r\n");

	// This is the last response code we look for until the end of the message.
	server_parse($socket, "354", __LINE__);

	// Send the Subject Line...
	fputs($socket, "Subject: $subject\r\n");

	// Now the To Header.
	fputs($socket, "To: $mail_to\r\n");

	// Now any custom headers....
	fputs($socket, "$headers\r\n\r\n");

	// Ok now we are ready for the message...
	fputs($socket, "$message\r\n");

	// Ok the all the ingredients are mixed in let's cook this puppy...
	fputs($socket, ".\r\n");
	server_parse($socket, "250", __LINE__);

	// Now tell the server we are done and close the socket...
	fputs($socket, "QUIT\r\n");
	fclose($socket);

	return TRUE;
}

   define("IMAGE_FLIP_HORIZONTAL",    1);
   define("IMAGE_FLIP_VERTICAL",    2);
   define("IMAGE_FLIP_BOTH",    3);

function ImageFlip($imgsrc, $type) {
   $width = imagesx($imgsrc);
   $height = imagesy($imgsrc);

   $imgdest = imagecreatetruecolor($width, $height);

   switch( $type )
       {
       // mirror wzgl. osi
       case IMAGE_FLIP_HORIZONTAL:
           for( $y=0 ; $y<$height ; $y++ )
               imagecopy($imgdest, $imgsrc, 0, $height-$y-1, 0, $y, $width, 1);
           break;

       case IMAGE_FLIP_VERTICAL:
           for( $x=0 ; $x<$width ; $x++ )
               imagecopy($imgdest, $imgsrc, $width-$x-1, 0, $x, 0, 1, $height);
           break;

       case IMAGE_FLIP_BOTH:
           for( $x=0 ; $x<$width ; $x++ )
               imagecopy($imgdest, $imgsrc, $width-$x-1, 0, $x, 0, 1, $height);

           $rowBuffer = imagecreatetruecolor($width, 1);
           for( $y=0 ; $y<($height/2) ; $y++ )
               {
               imagecopy($rowBuffer, $imgdest  , 0, 0, 0, $height-$y-1, $width, 1);
               imagecopy($imgdest  , $imgdest  , 0, $height-$y-1, 0, $y, $width, 1);
               imagecopy($imgdest  , $rowBuffer, 0, $y, 0, 0, $width, 1);
               }

           imagedestroy( $rowBuffer );
           break;
       }

   return( $imgdest );
}

function GetAllCompanyes () {

	$c_r = mysql_query("select * from companyes order by id");

    $i = 1;
    while ($res = mysql_fetch_assoc($c_r)) {
    	$out[$i] = $res;
        $i++;
    }

	return $out;
}

function GetActiveCompany () {

	global $lang;

	$c_r = mysql_query("select * from companyes where isactive=1");

    $out = mysql_fetch_assoc($c_r);

    if ($lang == 'ru')
    	$out['name'] = $out['realname'];
    else
    	$out['realname'] = $out['name'];

	return $out;

}


function GetCompanyById($id) {

	global $lang;

	$c_r = mysql_query("select * from companyes where id='$id'");

    $out = mysql_fetch_assoc($c_r);

    if ($lang == 'ru')
    	$out['name'] = $out['realname'];
    else
    	$out['realname'] = $out['name'];

	return $out;

}

function GetActiveWar() {

	$c_r = mysql_query("select max(id) as id from war");

    $out = mysql_fetch_assoc($c_r);

    $out = $out[id];

	return $out;

}

function GetActiveWarCompanyes() {

	global $SLANG;
    global $lang;

	$warid = GetActiveWar();

    $comp_r = mysql_query("select * from mission where warid='$warid' order by companyid DESC, id");

    while ($c = mysql_fetch_assoc($comp_r)) {

    	if ($c[WINNERID]) {

        	$companyid = $c[companyid];

			$out[$companyid][data] = GetCompanyById($companyid);

        	if ($c[WINNERID] == 1)
            {
	        	$out[$companyid][winnerid] = 1;
	        	$out[$companyid][winner] = $SLANG[$lang][sovietunion];
	        	$out[$companyid]['WON_HOW'] = $c["WON_HOW"];
            }
            elseif ($c[WINNERID] == 2)
            {
	        	$out[$companyid][winnerid] = 2;
	        	$out[$companyid][winner] = $SLANG[$lang][germany];
	        	$out[$companyid]['WON_HOW'] = $c["WON_HOW"];
            }

        }

    }

    return $out;

}

function GetWinBestWarCompanyes($id) {

	global $SLANG;
    global $lang;

    $comp_r = mysql_query("select * from best_in_war where warid='$id' and typeOf='m'");

    while ($c = mysql_fetch_assoc($comp_r)) {

    	if ($c[army]) {

			$out[name_id] = $c["callsign"];

        	if ($c[army] == 1)
            {
	        	$out[winnerid] = 1;
	        	$out[winner] = $SLANG[$lang][sovietunion];
	        	$out['WON_HOW'] = $c["rank"];
            }
            elseif ($c[army] == 2)
            {
	        	$out[winnerid] = 2;
	        	$out[winner] = $SLANG[$lang][germany];
	        	$out['WON_HOW'] = $c["rank"];
            }

        }

    }

    return $out;

}

function GetPlaneNameById($id) {

	$p_r = mysql_query("select name from aircrafts where id='$id'");

    $p = mysql_fetch_assoc($p_r);

    return $p[name];

}

function GetPlaneIdByName($name) {

	$p_r = mysql_query("select id from aircrafts where name='$name'");

    $p = mysql_fetch_assoc($p_r);

    return $p[id];

}

function GetBaseById($id) {

	$r = mysql_query("select * from fields_discr where id='$id'");

    $out = mysql_fetch_assoc($r);

    return $out;

}

function GetSquadRankSum($squad) {

	global $RANK;

	$sum =  $squad[rgiven1]*$RANK[1][1][price]
    		+
			$squad[rgiven2]*$RANK[1][2][price]
    		+
			$squad[rgiven3]*$RANK[1][3][price]
    		+
			$squad[rgiven4]*$RANK[1][4][price]
    		+
			$squad[rgiven5]*$RANK[1][5][price]
    		+
			$squad[rgiven6]*$RANK[1][6][price]
    		+
			$squad[rgiven7]*$RANK[1][7][price]
    		+
			$squad[rgiven8]*$RANK[1][8][price]
    		+
			$squad[rgiven9]*$RANK[1][9][price]
    		+
			$squad[rgiven10]*$RANK[1][10][price];

    return $sum;

}

function GetAllPlanesetsRating($army,$type,$rating) {


    $companyes = GetAllCompanyes ();

    $cc = count($companyes);

	foreach ($companyes as $company) {

    	$cid = $company["id"];

		$pl_r = mysql_query("select planeid,lineid,company_id,rating from planeset_discr where army='$army' and typeOf='$type' and rating<='$rating' and company_id='$cid' order by company_id,planeid");
//echo "select planeid,lineid,company_id from planeset_discr where army='$army' and typeOf='$type' and company_id='$cid' order by company_id,planeid";
        $i = 0;
        while ($pl = mysql_fetch_assoc($pl_r)) {

        	$lineid = $pl[lineid];
            $company_id = $pl[company_id];

        	$out[$lineid][$company_id][planeid] = $pl[planeid];
        	$out[$lineid][$company_id][planename] = GetPlaneNameById($pl[planeid]);
        	$out[$lineid][$company_id][rating] = $pl[rating];

            $i++;

        }

    }

    return $out;

}

function GetAllPlanesets($army,$type) {

    $companyes = GetAllCompanyes ();

    $cc = count($companyes);

	foreach ($companyes as $company) {

    	$cid = $company["id"];

		$pl_r = mysql_query("select planeid,lineid,company_id,rating from planeset_discr where army='$army' and typeOf='$type' and company_id='$cid' order by company_id,planeid");
//echo "select planeid,lineid,company_id from planeset_discr where army='$army' and typeOf='$type' and company_id='$cid' order by company_id,planeid";
        $i = 0;
        while ($pl = mysql_fetch_assoc($pl_r)) {

        	$lineid = $pl[lineid];
            $company_id = $pl[company_id];

        	$out[$lineid][$company_id][planeid] = $pl[planeid];
        	$out[$lineid][$company_id][rating] = $pl[rating];
        	$out[$lineid][$company_id][planename] = GetPlaneNameById($pl[planeid]);

            $i++;

        }

    }

    return $out;

}


function GetDivisionSquads ($did) {

	$sqp_r = mysql_query("select id, name from squadrons where divisionid='$did' or divisionid=-'$did' order by name");

    $i=0;
    while ($res = mysql_fetch_assoc($sqp_r)) {
    	$out[$i] = $res;
        $i++;
    }

//echo var_dump($out);

    return $out;

}

function GetAllFreeSquads ($armyid) {

	$sqp_r = mysql_query("select id, name from squadrons where divisionid<=0 and army='$armyid' order by name");

    $i=0;
    while ($res = mysql_fetch_assoc($sqp_r)) {
    	$out[$i] = $res;
        $i++;
    }

//echo var_dump($out);

    return $out;

}

function GetAllSquadPilots ($sqid) {

	$sqp_r = mysql_query("select * from finalpilots where squadronid=$sqid order by id");

    $squad = GetSquadById($sqid);

    $i=0;
    while ($res = mysql_fetch_assoc($sqp_r)) {

    	$out[$i] = $res;

	    $comp_r = mysql_query("select companyid from sorties where pilotid='$res[pilotid]' group by companyid");
	    while ($compres = mysql_fetch_assoc($comp_r)) {
	        $c = $compres[companyid];
	        $out[$i][companyes][$c] = 1;
	    }

    	$is_banned_r = mysql_query("select * from banned where nick_mask='".$out[$i][callsign]."' and comment='Banned by squad commander'");
        if (mysql_num_rows($is_banned_r) > 0)
	        $out[$i][is_banned] = 1;
        else
	        $out[$i][is_banned] = 0;

        $redact_r = mysql_query("select email,callsign_count,callsign_max_count,email_count,email_max_count from pilots where id='".$res[pilotid]."'");
        $redact = mysql_fetch_assoc($redact_r);
		$out[$i][email] = $redact[email];

        if (($redact[callsign_count] < $redact[callsign_max_count] or $redact[email_count] < $redact[email_max_count]) and $squad[xoname] != $res[callsign] and $squad[coname] != $res[callsign])
        	$out[$i][is_redacted] = 1;
        else
        	$out[$i][is_redacted] = 0;

        $i++;
    }
	return $out;
}

function GetDivisionCoAndXo ($dvid) {

	$pilots_r = mysql_query("select f.callsign, f.id from finalpilots f, squadrons s where s.divisionid='$dvid' and f.squadronid=s.id and (s.comander=f.pilotid or s.xcomader=f.pilotid) order by id");

    $i=0;
    while ($res = mysql_fetch_assoc($pilots_r)) {

    	$out[$i] = $res;

        $i++;
    }
//echo var_dump($out);

    return $out;

}

function GetAllSquadPilotsRanks ($sqid) {

	$sqp_r = mysql_query("select rank, rank_date from finalpilots where squadronid='$sqid' order by id");

    $squad = GetSquadById($sqid);

    $i=0;
    while ($res = mysql_fetch_assoc($sqp_r)) {

    	$out[$i] = $res;

        $i++;
    }

//echo var_dump($out);

    return $out;

}

function GetAllSquadPilotsRanksAndCompanyes ($sqid) {

	$sqp_r = mysql_query("select pilotid, companyes, rank, rank_date from finalpilots where squadronid='$sqid' order by id");

    $squad = GetSquadById($sqid);

    $i=0;
    while ($res = mysql_fetch_assoc($sqp_r)) {

    	$out[$i] = $res;

        $out[$i][companyes] = unserialize($out[$i][companyes]);

        $i++;
    }


//echo var_dump($out);

    return $out;

}

function GetAllSquadPilotsCommonStat ($sqid,$order) {

	$sqp_r = mysql_query("
    select
		id,
		pilotid,
		squadronid,
		callsign,
   army,
   streak,
   gstreak,
   bomberkills,
   tankkills,
   artillerykills,
   shipkills,
   kills,
   gkills,
   ks,
   gs,
   kd,
   gks,
   gkd,
   ground,
   rank,
   rank_date,
   N,
   lastsortie,
   maxsgkills,
   maxskills,
   award1,
   award2,
   award3,
   award4,
   award5,
   award6,
   award7,
   award8,
   award9,
   award10,
   award11,
   award12,
   award13,
   award14,
   award15,
   award16,
   award17,
   award18,
   award19,
   award20,
   award21,
   award22,
   award23,
   award24,
   award25,
   award26,
   award27,
   award28,
   award29,
   award30,
   award31,
   award1_date,
   award2_date,
   award3_date,
   award4_date,
   award5_date,
   award6_date,
   award7_date,
   award8_date,
   award9_date,
   award10_date,
   award11_date,
   award12_date,
   award13_date,
   award14_date,
   award15_date,
   award16_date,
   award17_date,
   award18_date,
   award19_date,
   award20_date,
   award21_date,
   award22_date,
   award23_date,
   award24_date,
   award25_date,
   award26_date,
   award27_date,
   award28_date,
   award29_date,
   award30_date,
   award31_date,
   ftime,
   fibull,
   hiabull,
   hibull,
   firock,
   hirock,
   fibomb,
   hibomb,
   score,
   bom+air as aair,
   air,
   bom,
   sair,
   tank,
   wag,
   art,
   car,
   aaa,
   ship,
   cv,
   bb,
   ca,
   dd,
   ss,
   TOFFS,
   DIED,
   CAPTURED,
   BAIL,
   DIED+CAPTURED+BAIL as planelose,
   TKON,
   CRASHED,
   DISCO,
   KICK,
   DIEDISCO,
   sorties,
   visible,
   wound,
   tkonwound,
   tkonfight,
   fuel,
   ammo,
   repair,
   addfuel,
   addammo,
   addrepair,
   dfuel,
   dammo,
   drepair,

   regdate

    from
    	finalpilots
    where
    	squadronid=$sqid $order
        ");

    $i=0;
    while ($res = mysql_fetch_assoc($sqp_r)) {

    	$out[pilots][$i] = $res;

    	$is_banned_r = mysql_query("select * from banned where nick_mask='".$out[$i][callsign]."'");
        if (mysql_num_rows($is_banned_r) > 0)
	        $out[pilots][$i][is_banned] = 1;
        else
	        $out[pilots][$i][is_banned] = 0;

		$out[pilots][$i][fig] = $out[pilots][$i][air];

		$out[total][deths] += $out[pilots][$i][DIED];
		$out[total][captured] += $out[pilots][$i][CAPTURED];
		$out[total][bailed] += $out[pilots][$i][BAIL];
		$out[total][planelose] += ($out[pilots][$i][CAPTURED]+$out[pilots][$i][BAIL]+$out[pilots][$i][DIED]+$out[pilots][$i][DISCO]+$out[pilots][$i][DIEDISCO]);
		$out[total][pilotlose] += ($out[pilots][$i][CAPTURED]+$out[pilots][$i][DIED]+$out[pilots][$i][DISCO]+$out[pilots][$i][DIEDISCO]);

		$out[total][time] += $out[pilots][$i][ftime];
		$out[total][aair] += $out[pilots][$i][air]+$out[pilots][$i][bom];
		$out[total][bom] += $out[pilots][$i][bom];
		$out[total][fig] += $out[pilots][$i][air];
		$out[total][k] += $out[pilots][$i][air]+$out[pilots][$i][bom];
		$out[total][gk] += $out[pilots][$i][ground];
		$out[total][d] += ($out[pilots][$i][DIED]+$out[pilots][$i][CAPTURED]+$out[pilots][$i][DIEDISCO]);
		$out[total][s] += $out[pilots][$i][sorties];
		$out[total][destroy] += $out[pilots][$i][ground];

		$out[total][tank] += $out[pilots][$i][tank];
		$out[total][wag] += $out[pilots][$i][wag];
		$out[total][art] += $out[pilots][$i][art];
		$out[total][sair] += $out[pilots][$i][sair];
		$out[total][car] += $out[pilots][$i][car];
		$out[total][aaa] += $out[pilots][$i][aaa];
		$out[total][ship] += $out[pilots][$i][ship];
		$out[total][TOFFS] += $out[pilots][$i][TOFFS];
		$out[total][DIED] += $out[pilots][$i][DIED]+$out[pilots][$i][DIEDISCO];
		$out[total][CAPTURED] += $out[pilots][$i][CAPTURED];
		$out[total][BAIL] += $out[pilots][$i][BAIL];
		$out[total][TKON] += $out[pilots][$i][TKON];
		$out[total][CRASHED] += $out[pilots][$i][CRASHED];
		$out[total][DISCO] += $out[pilots][$i][DISCO]+$out[pilots][$i][DIEDISCO];
		$out[total][sorties] += $out[pilots][$i][sorties];
		$out[total][wound] += $out[pilots][$i][wound];
		$out[total][tkonfight] += $out[pilots][$i][tkonfight];

		$out[total][fuel] += $out[pilots][$i][fuel];
		$out[total][addfuel] += $out[pilots][$i][addfuel];
		$out[total][dfuel] += $out[pilots][$i][dfuel];
		$out[total][ammo] += $out[pilots][$i][ammo];
		$out[total][addammo] += $out[pilots][$i][addammo];
		$out[total][dammo] += $out[pilots][$i][dammo];
		$out[total][repair] += $out[pilots][$i][repair];
		$out[total][addrepair] += $out[pilots][$i][addrepair];
		$out[total][drepair] += $out[pilots][$i][drepair];

        $i++;
    }

    return $out;

}

function GetAllDivisionSquadsCommonStat ($divid,$order) {
	$sqp_r = mysql_query("
    select
        DIED+CAPTURED+BAIL as planelose,
        wound,
        deaths,
        TKON,
        BAIL,
        CRASHED,
        CAPTURED,
        DIED,
        MIA,
        KICK,
        DIEDISCO,
        sorties,
        fuel,
        ammo,
        repair,
        addfuel,
        addammo,
        addrepair,
        dfuel,
        dammo,
        drepair
    from
    	squadrons
    where
    	divisionid=$divid
        ");

    $i=0;
    while ($res = mysql_fetch_assoc($sqp_r)) {
    	$out[pilots][$i] = $res;
		//$out[pilots][$i][fig] = $out[pilots][$i][air];

		$out[total][deths] += $out[pilots][$i][DIED];
		$out[total][captured] += $out[pilots][$i][CAPTURED];
		$out[total][bailed] += $out[pilots][$i][BAIL];
		$out[total][planelose] += ($out[pilots][$i][CAPTURED]+$out[pilots][$i][BAIL]+$out[pilots][$i][DIED]+$out[pilots][$i][DISCO]+$out[pilots][$i][DIEDISCO]);
		$out[total][pilotlose] += ($out[pilots][$i][CAPTURED]+$out[pilots][$i][DIED]+$out[pilots][$i][DISCO]+$out[pilots][$i][DIEDISCO]);

		//$out[total][time] += $out[pilots][$i][ftime];
		$out[total][aair] += $out[pilots][$i][air]+$out[pilots][$i][bom];
		$out[total][bom] += $out[pilots][$i][bom];
		$out[total][fig] += $out[pilots][$i][air];
		$out[total][k] += $out[pilots][$i][air]+$out[pilots][$i][bom];
		$out[total][gk] += $out[pilots][$i][ground];
		$out[total][d] += ($out[pilots][$i][DIED]+$out[pilots][$i][CAPTURED]+$out[pilots][$i][DIEDISCO]);
		$out[total][s] += $out[pilots][$i][sorties];
		$out[total][destroy] += $out[pilots][$i][ground];

		$out[total][tank] += $out[pilots][$i][tank];
		$out[total][wag] += $out[pilots][$i][wag];
		$out[total][art] += $out[pilots][$i][art];
		$out[total][sair] += $out[pilots][$i][sair];
		$out[total][car] += $out[pilots][$i][car];
		$out[total][aaa] += $out[pilots][$i][aaa];
		$out[total][ship] += $out[pilots][$i][ship];
		$out[total][TOFFS] += $out[pilots][$i][TOFFS];
		$out[total][DIED] += $out[pilots][$i][DIED]+$out[pilots][$i][DIEDISCO];
		$out[total][CAPTURED] += $out[pilots][$i][CAPTURED];
		$out[total][BAIL] += $out[pilots][$i][BAIL];
		$out[total][TKON] += $out[pilots][$i][TKON];
		$out[total][CRASHED] += $out[pilots][$i][CRASHED];
		$out[total][DISCO] += $out[pilots][$i][DISCO]+$out[pilots][$i][DIEDISCO];
		$out[total][sorties] += $out[pilots][$i][sorties];
		$out[total][wound] += $out[pilots][$i][wound];
		$out[total][tkonfight] += $out[pilots][$i][TKON];

		$out[total][fuel] += $out[pilots][$i][fuel];
		$out[total][addfuel] += $out[pilots][$i][addfuel];
		$out[total][dfuel] += $out[pilots][$i][dfuel];
		$out[total][ammo] += $out[pilots][$i][ammo];
		$out[total][addammo] += $out[pilots][$i][addammo];
		$out[total][dammo] += $out[pilots][$i][dammo];
		$out[total][repair] += $out[pilots][$i][repair];
		$out[total][addrepair] += $out[pilots][$i][addrepair];
		$out[total][drepair] += $out[pilots][$i][drepair];

        $i++;
    }

    return $out;

}

function RevealAllBannedSquadPilots($sqid) {

	$sqp_r = mysql_query("select callsign from pilots where squadronid=$sqid order by id");

    while ($out = mysql_fetch_assoc($sqp_r)) {

    	$is_banned_r = mysql_query("delete from banned where nick_mask='".$out[callsign]."' and comment='Banned by squad commander'");

    }

}

function GetSquadPlanes ($sqid) {

	$ac = GetActiveCompany ();

	$planes_r = mysql_query("select * from planesets where squad_id='$sqid' and Count>0");

    while ($res = mysql_fetch_assoc($planes_r)) {

    	$out[] = GetPlaneNameById($res[plane_id])."(".$res[Count].")";

    }

    return $out;

}

function GetSquadPlanesIds ($sqid) {

	$ac = GetActiveCompany ();

	$planes_r = mysql_query("select * from planesets where squad_id='$sqid' and Count>0");

    while ($res = mysql_fetch_assoc($planes_r)) {

    	$out[$res[plane_id]] = $res[Count];

    }

    return $out;

}

function GetDivisionStatus ($did) {

	global $SiteURL;

    $os_r = mysql_query("select id,tag,name,typeOf from squadrons where divisionid='$did' order by name");

    while ($res =mysql_fetch_assoc($os_r))
	    $out[squads][] =  "<a href=\"${SiteURL}squads/".$res[id]."/index.html\">".$res[tag]."</a>";

    return $out;

}

function GetDivisionWaitStatus ($did) {

	global $SiteURL;

    $os_r = mysql_query("select id,tag,name,typeOf from squadrons where divisionid=-'$did' order by name");

    while ($res =mysql_fetch_assoc($os_r))
	    $out[squads][] =  "<a href=\"${SiteURL}squads/".$res[id]."/index.html\">".$res[tag]."</a>";

    return $out;

}

function GetBaseStatus ($fid) {

	global $SiteURL;

	$fid_r = mysql_query("select * from fields_discr where id='$fid'");

    $out[field] = mysql_fetch_assoc($fid_r);

    $os_r = mysql_query("select id,tag,name,typeOf from squadrons where fieldid='$fid'");

    while ($res =mysql_fetch_assoc($os_r))
	    $out[squads][] =  "<a href=\"${SiteURL}squads/".$res[id]."/index.html\">".$res[tag]."</a>";

    return $out;

}

function GetSquadSupply ($sid) {

	$squad_r = mysql_query("select * from squadrons where id='$sid'");
	$out = mysql_fetch_assoc($squad_r);

    return $out;
}

function GetSquadPlane($sqid) {

	$sq = GetSquadById($sqid);

    $ac = GetActiveCompany();

    $r = mysql_query("select planeid from planeset_discr where lineid='$sq[lineid]' and army='$sq[army]' and typeOf='$sq[typeOf]' and company_id='$ac[id]'");


	$res = mysql_fetch_assoc($r);

    return $res[planeid];

}

function GetAllArmyFields($army) {

	$f_r = mysql_query("select * from fields_discr where army='$army'");

    while ($res = mysql_fetch_assoc($f_r)) {

    	$out[] = $res;

    }

    return $out;

}

function GetGameTime() {

	$r = mysql_query("
    select
    	gametime,
	    gamedate
    from
    	mission order by id DESC LIMIT 0,1");

    $out = mysql_fetch_assoc($r);

    return $out[gametime]." ".$out[gamedate];

}

function GetGameWeather() {

	$r = mysql_query("select pogoda from mission order by id DESC LIMIT 0,1");

    $out = mysql_fetch_assoc($r);

    $acid = GetActiveCompany();
    $acid = $acid[id];

    if (($acid == 5 or $acid ==8) and $out[pogoda] ==5) $out[pogoda] = "51";
    return "pogoda".$out[pogoda].".jpg";

}

function GetMissionBriefings() {

	global $lang;

	$r = mysql_query("select brief_red_".$lang.", brief_blue_".$lang." from mission order by id DESC LIMIT 0,1");

    $res = mysql_fetch_assoc($r);

    $out[red] = $res["brief_red_".$lang];
    $out[blue] = $res["brief_blue_".$lang];

    return $out;
}

function GetMissionImage() {

	$r = mysql_query("select mapa from mission order by id DESC LIMIT 0,1");

    $res = mysql_fetch_assoc($r);

    return $res[mapa];

}

function GetSquareByCoords($x,$y) {

	$lar = array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","BB","CC","DD","EE","FF","GG","HH","II","JJ","KK","LL","MM","NN","OO","PP","QQ","RR","SS","TT","UU","VV","WW","XX","YY","ZZ");
    $nar = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52);

    $cx = floor($x / sqadx);
    $cy = floor($y / sqady);

    $sq = $lar[$cx].$nar[$cy];

    return $sq;

}

function GetAirEvents($time=3600) {

	$r = mysql_query("select * from killboard where killerground=0 and killedground=0 and ".time()."-UNIX_TIMESTAMP(realdatetime)<=".$time." and (typeofaction=2 or typeofaction=12 or typeofaction=13)");

    while ($res = mysql_fetch_assoc($r)) {

    	$sq = GetSquareByCoords($res[X],$res[Y]);
    	$map[$sq] += 1;

    }

    if (is_array($map) and count($map)>0) {
	    $map = array_flip($map);
	    arsort($map,SORT_NUMERIC);
	    $map = array_flip($map);
    }

    return $map;

}

function GetGroundEvents($time=3600) {

	$r = mysql_query("select * from killboard where killerground=1 and killedground=1 and ".time()."-UNIX_TIMESTAMP(realdatetime)<=".$time." and (typeofaction=2 or typeofaction=12 or typeofaction=13)");

    while ($res = mysql_fetch_assoc($r)) {

    	$sq = GetSquareByCoords($res[X],$res[Y]);
    	$map[$sq] += 1;

    }

    if (is_array($map) and count($map)>0) {
	    $map = array_flip($map);
	    arsort($map,SORT_NUMERIC);
	    $map = array_flip($map);
    }

    return $map;

}

function GetBomberEvents($time=3600) {

	$r = mysql_query("select * from killboard where killerground=0 and killedground=1 and ".time()."-UNIX_TIMESTAMP(realdatetime)<=".$time." and (typeofaction=2 or typeofaction=12 or typeofaction=13)");

    while ($res = mysql_fetch_assoc($r)) {

    	$sq = GetSquareByCoords($res[X],$res[Y]);
    	$map[$sq] += 1;

    }

    if (is_array($map) and count($map)>0) {
	    $map = array_flip($map);
	    arsort($map,SORT_NUMERIC);
	    $map = array_flip($map);
    }

    return $map;

}


function FillTemplateCommonData() {

	global $TPmain;
    global $lang;
    global $MONTHS;

	$acomp = GetActiveCompany ();

    //let's fill resorsec bar
    $TPmain->AssignTag("<!--redfuel-->",round($acomp[current1fuel]/($acomp[total1fuel]+1),2)*100);
    $TPmain->AssignTag("<!--redammo-->",round($acomp[current1ammo]/($acomp[total1ammo]+1),2)*100);
    $TPmain->AssignTag("<!--redrepair-->",round($acomp[current1repair]/($acomp[total1repair]+1),2)*100);

    $TPmain->AssignTag("<!--bluefuel-->",round($acomp[current2fuel]/($acomp[total2fuel]+1),2)*100);
    $TPmain->AssignTag("<!--blueammo-->",round($acomp[current2ammo]/($acomp[total2ammo]+1),2)*100);
    $TPmain->AssignTag("<!--bluerepair-->",round($acomp[current2repair]/($acomp[total2repair]+1),2)*100);

    //Let's fill time and weather bar
    $gametime = GetGameTime();
    $gametime = explode(" ",$gametime);

    $gametimestamp = explode(":",$gametime[0]);

    $TPmain->AssignTag("<!--gametime-->",$gametimestamp[0].":".$gametimestamp[1]);
    $gametime = explode("-",$gametime[1]);
    $month = (int)$gametime[1];

    $TPmain->AssignTag("<!--gamemonth-->",$MONTHS[$lang][$month]);
    $TPmain->AssignTag("<!--gameday-->",$gametime[2]);
    $TPmain->AssignTag("<!--gameyear-->",$gametime[0]);


    $weather = GetGameWeather();
    $TPmain->AssignTag("<!--weather-->",$weather);


}


function GetCORank ($n) {

	if ($n>=4 and $n<=8)
    	return 2;

	if ($n>=9 and $n<=20)
    	return 3;

	if ($n>=21 and $n<=60)
    	return 5;

	if ($n>=61 and $n<=80)
    	return 7;

	if ($n>=81 and $n<=99)
    	return 9;

}

function GetXORank ($n) {

	if ($n>=4 and $n<=8)
    	return 1;

	if ($n>=9 and $n<=20)
    	return 2;

	if ($n>=21 and $n<=60)
    	return 4;

	if ($n>=61 and $n<=80)
    	return 6;

	if ($n>=81 and $n<=99)
    	return 8;

}

function GetRankPot($n) {

	if ($n>=4 and $n<=8)
    	return 0;

	if ($n>=9 and $n<=20)
    	return 400;

	if ($n>=21 and $n<=60)
    	return 3800;

	if ($n>=61 and $n<=80)
    	return 10300;

	if ($n>=81 and $n<=99)
    	return 22300;

}


function GetCompanyStat($cid=0) {

	if (!$cid) { $cid = GetActiveCompany(); $cid = $cid[id]; }
    $warid = GetActiveWar();

    $red_r = mysql_query(
    	"select
        count(*) as sorties,
		round(sum((UNIX_TIMESTAMP(s.endtime)-UNIX_TIMESTAMP(s.starttime)))/3600,2)+0 as ftime,
		sum(s.FiBull) as fibull,
        sum(s.HiBull) as hibull,
		sum(s.HiABull) as hiabull,
        sum(s.FiRock) as firock,
		sum(s.HiRock) as hirock,
        sum(s.FiBomb) as fibomb,
		sum(s.HiBomb) as hibomb,
		sum(s.score)+0 as score,
        sum(s.eAir)-sum(s.eBom)+0 as air,
        sum(s.eAir)+0 as kills,
        sum(s.eBom)+0 as bom,
        sum(s.eSair)+0 as sair,
		sum(s.eTank)+0 as tank,
        sum(s.eWag)+0 as wag ,
		sum(s.eArt)+0 as art,
        sum(s.eCar)+0 as car,
		sum(s.eAaa)+0 as aaa,
        sum(s.eShip)+0 as ship,

        sum(s.dfuel)+0 as dfuel,
        sum(s.dammo)+0 as dammo,
        sum(s.drepair)+0 as drepair,

        sum(if(s.Wound!='0',1,0)) as wound,
        sum(if((if(s.Wound!='0',1,0)+if(s.SortieEND='TKON',1,0))=2,1,0)) as tkonwound,

        sum(s.eAir) /
				(sum(if(s.SortieEND='DIED',1,0) or if(s.SortieEND='DIEDISCO',1,0) or if(s.SortieEND='CAPTURED',1,0))+1) as kd,

		sum(s.eAir) / count(*) as ks,

        ( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip) ) as ground,
		( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip))
        		/
        (sum(if(s.SortieEND='DIED',1,0) or if(s.SortieEND='DIEDISCO',1,0) or if(s.SortieEND='CAPTURED',1,0))+1) as gkd,

		( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip))
        		/
        count(*) as gks

        FROM
            sorties as s
        WHERE
		    (
            	(UNIX_TIMESTAMP(s.endtime)-UNIX_TIMESTAMP(s.starttime))>=60*15
					or
        		(s.eSAir+s.eTank+s.eCar+s.eArt+s.eAaa+s.eWag+s.eShip)>0
            		or
        		s.SortieEND<>'TKON'
                	or
                s.eAir>0
                	or
                s.addammo>0
                	or
                s.addfuel>0
                	or
                s.addrepair>0
                	or
                s.dfuel>0
                	or
                s.dammo>0
                	or
                s.drepair>0
            )
        		and
        	SortieEND != 'MIA'
            	and
        	SortieEND != 'KICK'
            	and
        	SortieEND != 'DIEDISCO'
				and
         	companyid='$cid'
				and
            armyid=1
                ");

	$out[red] = mysql_fetch_assoc($red_r);

    $blue_r = mysql_query(
    	"select
        count(*) as sorties,
		round(sum((UNIX_TIMESTAMP(s.endtime)-UNIX_TIMESTAMP(s.starttime)))/3600,2)+0 as ftime,
		sum(s.FiBull) as fibull,
        sum(s.HiBull) as hibull,
		sum(s.HiABull) as hiabull,
        sum(s.FiRock) as firock,
		sum(s.HiRock) as hirock,
        sum(s.FiBomb) as fibomb,
		sum(s.HiBomb) as hibomb,
		sum(s.score)+0 as score,
        sum(s.eAir)-sum(s.eBom)+0 as air,
        sum(s.eAir)+0 as kills,
        sum(s.eBom)+0 as bom,
        sum(s.eSair)+0 as sair,
		sum(s.eTank)+0 as tank,
        sum(s.eWag)+0 as wag ,
		sum(s.eArt)+0 as art,
        sum(s.eCar)+0 as car,
		sum(s.eAaa)+0 as aaa,
        sum(s.eShip)+0 as ship,

        sum(s.dfuel)+0 as dfuel,
        sum(s.dammo)+0 as dammo,
        sum(s.drepair)+0 as drepair,

        sum(if(s.Wound!='0',1,0)) as wound,
        sum(if((if(s.Wound!='0',1,0)+if(s.SortieEND='TKON',1,0))=2,1,0)) as tkonwound,

        sum(s.eAir) /
				(sum(if(s.SortieEND='DIED',1,0) or if(s.SortieEND='DIEDISCO',1,0) or if(s.SortieEND='CAPTURED',1,0))+1) as kd,

		sum(s.eAir) / count(*) as ks,

        ( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip) ) as ground,
		( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip))
        		/
        (sum(if(s.SortieEND='DIED',1,0) or if(s.SortieEND='DIEDISCO',1,0) or if(s.SortieEND='CAPTURED',1,0))+1) as gkd,

		( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip))
        		/
        count(*) as gks

        FROM
            sorties as s
        WHERE
		    (
            	(UNIX_TIMESTAMP(s.endtime)-UNIX_TIMESTAMP(s.starttime))>=60*15
					or
        		(s.eSAir+s.eTank+s.eCar+s.eArt+s.eAaa+s.eWag+s.eShip)>0
            		or
        		s.SortieEND<>'TKON'
                	or
                s.eAir>0
                	or
                s.addammo>0
                	or
                s.addfuel>0
                	or
                s.addrepair>0
                	or
                s.dfuel>0
                	or
                s.dammo>0
                	or
                s.drepair>0
            )
        		and
        	SortieEND != 'MIA'
            	and
        	SortieEND != 'KICK'
            	and
        	SortieEND != 'DIEDISCO'
				and
         	companyid='$cid'
				and
            armyid=2
                ");

	$out[blue] = mysql_fetch_assoc($blue_r);


	return $out;
}

function GetWarStat($wid=0) {

	if (!$cid) { $cid = GetActiveCompany(); $cid = $cid[id]; }
    $warid = GetActiveWar();

    $red_r = mysql_query(
    	"select
        count(*) as sorties,
		round(sum((UNIX_TIMESTAMP(s.endtime)-UNIX_TIMESTAMP(s.starttime)))/3600,2)+0 as ftime,
		sum(s.FiBull) as fibull,
        sum(s.HiBull) as hibull,
		sum(s.HiABull) as hiabull,
        sum(s.FiRock) as firock,
		sum(s.HiRock) as hirock,
        sum(s.FiBomb) as fibomb,
		sum(s.HiBomb) as hibomb,
		sum(s.score)+0 as score,
        sum(s.eAir)-sum(s.eBom)+0 as air,
        sum(s.eAir)+0 as kills,
        sum(s.eBom)+0 as bom,
        sum(s.eSair)+0 as sair,
		sum(s.eTank)+0 as tank,
        sum(s.eWag)+0 as wag ,
		sum(s.eArt)+0 as art,
        sum(s.eCar)+0 as car,
		sum(s.eAaa)+0 as aaa,
        sum(s.eShip)+0 as ship,

        sum(s.dfuel)+0 as dfuel,
        sum(s.dammo)+0 as dammo,
        sum(s.drepair)+0 as drepair,

        sum(if(s.Wound!='0',1,0)) as wound,
        sum(if((if(s.Wound!='0',1,0)+if(s.SortieEND='TKON',1,0))=2,1,0)) as tkonwound,

        sum(s.eAir) /
				(sum(if(s.SortieEND='DIED',1,0) or if(s.SortieEND='DIEDISCO',1,0) or if(s.SortieEND='CAPTURED',1,0))+1) as kd,

		sum(s.eAir) / count(*) as ks,

        ( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip) ) as ground,
		( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip))
        		/
        (sum(if(s.SortieEND='DIED',1,0) or if(s.SortieEND='DIEDISCO',1,0) or if(s.SortieEND='CAPTURED',1,0))+1) as gkd,

		( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip))
        		/
        count(*) as gks

        FROM
            sorties as s
        WHERE
		    (
            	(UNIX_TIMESTAMP(s.endtime)-UNIX_TIMESTAMP(s.starttime))>=60*15
					or
        		(s.eSAir+s.eTank+s.eCar+s.eArt+s.eAaa+s.eWag+s.eShip)>0
            		or
        		s.SortieEND<>'TKON'
                	or
                s.eAir>0
                	or
                s.addammo>0
                	or
                s.addfuel>0
                	or
                s.addrepair>0
                	or
                s.dfuel>0
                	or
                s.dammo>0
                	or
                s.drepair>0
            )
        		and
        	SortieEND != 'MIA'
            	and
        	SortieEND != 'KICK'
            	and
        	SortieEND != 'DIEDISCO'
				and
            armyid=1
                ");

	$out[red] = mysql_fetch_assoc($red_r);

    $blue_r = mysql_query(
    	"select
        count(*) as sorties,
		round(sum((UNIX_TIMESTAMP(s.endtime)-UNIX_TIMESTAMP(s.starttime)))/3600,2)+0 as ftime,
		sum(s.FiBull) as fibull,
        sum(s.HiBull) as hibull,
		sum(s.HiABull) as hiabull,
        sum(s.FiRock) as firock,
		sum(s.HiRock) as hirock,
        sum(s.FiBomb) as fibomb,
		sum(s.HiBomb) as hibomb,
		sum(s.score)+0 as score,
        sum(s.eAir)-sum(s.eBom)+0 as air,
        sum(s.eAir)+0 as kills,
        sum(s.eBom)+0 as bom,
        sum(s.eSair)+0 as sair,
		sum(s.eTank)+0 as tank,
        sum(s.eWag)+0 as wag ,
		sum(s.eArt)+0 as art,
        sum(s.eCar)+0 as car,
		sum(s.eAaa)+0 as aaa,
        sum(s.eShip)+0 as ship,

        sum(s.dfuel)+0 as dfuel,
        sum(s.dammo)+0 as dammo,
        sum(s.drepair)+0 as drepair,

        sum(if(s.Wound!='0',1,0)) as wound,
        sum(if((if(s.Wound!='0',1,0)+if(s.SortieEND='TKON',1,0))=2,1,0)) as tkonwound,

        sum(s.eAir) /
				(sum(if(s.SortieEND='DIED',1,0) or if(s.SortieEND='DIEDISCO',1,0) or if(s.SortieEND='CAPTURED',1,0))+1) as kd,

		sum(s.eAir) / count(*) as ks,

        ( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip) ) as ground,
		( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip))
        		/
        (sum(if(s.SortieEND='DIED',1,0) or if(s.SortieEND='DIEDISCO',1,0) or if(s.SortieEND='CAPTURED',1,0))+1) as gkd,

		( sum(s.eTank) + sum(s.eSair) + sum(s.eWag) + sum(s.eArt) + sum(s.eCar) + sum(s.eAaa) + sum(s.eShip))
        		/
        count(*) as gks

        FROM
            sorties as s
        WHERE
		    (
            	(UNIX_TIMESTAMP(s.endtime)-UNIX_TIMESTAMP(s.starttime))>=60*15
					or
        		(s.eSAir+s.eTank+s.eCar+s.eArt+s.eAaa+s.eWag+s.eShip)>0
            		or
        		s.SortieEND<>'TKON'
                	or
                s.eAir>0
                	or
                s.addammo>0
                	or
                s.addfuel>0
                	or
                s.addrepair>0
                	or
                s.dfuel>0
                	or
                s.dammo>0
                	or
                s.drepair>0
            )
        		and
        	SortieEND != 'MIA'
            	and
        	SortieEND != 'KICK'
            	and
        	SortieEND != 'DIEDISCO'
				and
            armyid=2
                ");

	$out[blue] = mysql_fetch_assoc($blue_r);


	return $out;
}

function getWarStatbyId($id)
{

	$war_r = mysql_query("SELECT * FROM war WHERE id='".intval($id)."'");

	if ($war = mysql_fetch_assoc($war_r))
	{
		return $war;
	}

	return '';


}

function getWarBestPilots($warid)
{
	global $VIEW;
    global $link;

	$f_pilots_r = mysql_query("SELECT * FROM best_in_war WHERE warid='".intval($warid)."' and typeOf='f' order by `kill` DESC");

	$out['bf'][] = '';

	while ($f_pilots = mysql_fetch_assoc($f_pilots_r))
	{
		if ($f_pilots['army'] ==1)
			$f_pilots['Flag'] = $VIEW[ASMALLFLAG];
        elseif ($f_pilots['army'] == 2) {
	        $f_pilots['Flag'] = $VIEW[BSMALLFLAG];
        }
        else
	        $f_pilots['Flag'] = $VIEW[NOFLAG];

		$f_pilots['Rank'] = GetRankByRankId($f_pilots['rank'],$f_pilots['army']);
		$f_pilots['ks'] = $f_pilots['kill'];

		$out['bf'][] = $f_pilots;
	}

	$f_pilots_r = mysql_query("SELECT * FROM best_in_war WHERE warid='".intval($warid)."' and typeOf='b' order by `kill` DESC");

	$out['bb'][] = '';

	while ($f_pilots = mysql_fetch_assoc($f_pilots_r))
	{
		if ($f_pilots['army'] ==1)
			$f_pilots['Flag'] = $VIEW[ASMALLFLAG];
        elseif ($f_pilots['army'] == 2) {
	        $f_pilots['Flag'] = $VIEW[BSMALLFLAG];
        }
        else
	        $f_pilots['Flag'] = $VIEW[NOFLAG];

	    $f_pilots['Rank'] = GetRankByRankId($f_pilots['rank'],$f_pilots['army']);
	    $f_pilots['ks'] = $f_pilots['kill'];

		$out['bb'][] = $f_pilots;
	}

	$f_pilots_r = mysql_query("SELECT * FROM best_in_war WHERE warid='".intval($warid)."' and typeOf='sb' order by `kill` DESC");

	$out['sb'][] = '';

	while ($f_pilots = mysql_fetch_assoc($f_pilots_r))
	{
		if ($f_pilots['army'] ==1)
			$f_pilots['Flag'] = $VIEW[ASMALLFLAG];
        elseif ($f_pilots['army'] == 2) {
	        $f_pilots['Flag'] = $VIEW[BSMALLFLAG];
        }
        else
	        $f_pilots['Flag'] = $VIEW[NOFLAG];

	    $f_pilots['Rank'] = $f_pilots['rank'];
	    $f_pilots['ks'] = $f_pilots['kill'];

		$out['sb'][] = $f_pilots;
	}

	$f_pilots_r = mysql_query("SELECT * FROM best_in_war WHERE warid='".intval($warid)."' and typeOf='sf' order by `kill` DESC");

	$out['sf'][] = '';

	while ($f_pilots = mysql_fetch_assoc($f_pilots_r))
	{
		if ($f_pilots['army'] ==1)
			$f_pilots['Flag'] = $VIEW[ASMALLFLAG];
        elseif ($f_pilots['army'] == 2) {
	        $f_pilots['Flag'] = $VIEW[BSMALLFLAG];
        }
        else
	        $f_pilots['Flag'] = $VIEW[NOFLAG];

	    $f_pilots['Rank'] = $f_pilots['rank'];
	    $f_pilots['ks'] = $f_pilots['kill'];

		$out['sf'][] = $f_pilots;
	}

	$f_pilots_r = mysql_query("SELECT * FROM best_in_war WHERE warid='".intval($warid)."' and typeOf='d' order by `kill` DESC");

	$out['div'][] = '';

	while ($f_pilots = mysql_fetch_assoc($f_pilots_r))
	{
		if ($f_pilots['army'] ==1)
			$f_pilots['Flag'] = $VIEW[ASMALLFLAG];
        elseif ($f_pilots['army'] == 2) {
	        $f_pilots['Flag'] = $VIEW[BSMALLFLAG];
        }
        else
	        $f_pilots['Flag'] = $VIEW[NOFLAG];

	    $f_pilots['Rank'] = $f_pilots['rank'];
	    $f_pilots['ks'] = $f_pilots['kill'];

		$out['div'][] = $f_pilots;
	}

	if (count($out['bf'])==1 && count($out['bb'])&& count($out['sb'])&& count($out['sf'])&& count($out['div'])==1)
	{
		$out['bf'][1]['Flag'] = $VIEW[NOFLAG];
		$out['bf'][2]['Flag'] = $VIEW[NOFLAG];
		$out['bf'][3]['Flag'] = $VIEW[NOFLAG];
		$out['bf'][4]['Flag'] = $VIEW[NOFLAG];
		$out['bf'][5]['Flag'] = $VIEW[NOFLAG];

		$out['bb'][1]['Flag'] = $VIEW[NOFLAG];
		$out['bb'][2]['Flag'] = $VIEW[NOFLAG];
		$out['bb'][3]['Flag'] = $VIEW[NOFLAG];
		$out['bb'][4]['Flag'] = $VIEW[NOFLAG];
		$out['bb'][5]['Flag'] = $VIEW[NOFLAG];

		$out['sf'][1]['Flag'] = $VIEW[NOFLAG];
		$out['sf'][2]['Flag'] = $VIEW[NOFLAG];
		$out['sf'][3]['Flag'] = $VIEW[NOFLAG];
		$out['sf'][4]['Flag'] = $VIEW[NOFLAG];
		$out['sf'][5]['Flag'] = $VIEW[NOFLAG];

		$out['sb'][1]['Flag'] = $VIEW[NOFLAG];
		$out['sb'][2]['Flag'] = $VIEW[NOFLAG];
		$out['sb'][3]['Flag'] = $VIEW[NOFLAG];
		$out['sb'][4]['Flag'] = $VIEW[NOFLAG];
		$out['sb'][5]['Flag'] = $VIEW[NOFLAG];

		$out['div'][1]['Flag'] = $VIEW[NOFLAG];
		$out['div'][2]['Flag'] = $VIEW[NOFLAG];
		$out['div'][3]['Flag'] = $VIEW[NOFLAG];
		$out['div'][4]['Flag'] = $VIEW[NOFLAG];
		$out['div'][5]['Flag'] = $VIEW[NOFLAG];
		$out['div'][6]['Flag'] = $VIEW[NOFLAG];
		$out['div'][7]['Flag'] = $VIEW[NOFLAG];
		$out['div'][8]['Flag'] = $VIEW[NOFLAG];
		$out['div'][9]['Flag'] = $VIEW[NOFLAG];
		$out['div'][10]['Flag'] = $VIEW[NOFLAG];
	}

	//var_dump($out);
	return $out;

}

function BattleReport () {

	global $VIEW;
	//$ac = GetActiveCompany ();

	$battle_r = mysql_query("SELECT b.*, m.x as x_curr, m.y as y_curr, if(m.x >= 0, COUNT(1), 0) as units_curr
		FROM
  			battle_report b
		LEFT OUTER JOIN mission_objects m ON (b.gid = m.gid)
		GROUP BY
  			b.gid
		ORDER BY
  			armychar DESC, id");

    $i = 1;

    while ($res = mysql_fetch_assoc($battle_r)) {

		$out[$i] = $res;

		if ($res['armychar'] == 'r')
			$out[$i]['Flag'] = $VIEW[ASMALLFLAG];
        elseif ($res['armychar'] =='b') {
	        $out[$i]['Flag'] = $VIEW[BSMALLFLAG];
        }
        else
	        $out[$i]['Flag'] = $VIEW[NOFLAG];


    	$i++;

    }

    return $out;

}

function GetPilotPoints ($pilotid) {

	global $VIEW;
    global $link;
    global $SERVER;


	$r = mysql_query("
    Select
    	s.id,
		s.eTank as tanks,
		s.eSAir + s.eCar + s.eArt + s.eAaa + s.eWag + s.eShip as gkills,
		s.dfuel, s.dammo, s.drepair,
		s.eAir as kills,
        s.starttime,
        s.starttime as rdt
    FROM
      	sorties as s
    WHERE
        s.pilotid='$pilotid'
            	and
		    (
            	(UNIX_TIMESTAMP(s.endtime)-UNIX_TIMESTAMP(s.starttime))>=60*15
					or
        		(s.eSAir+s.eTank+s.eCar+s.eArt+s.eAaa+s.eWag+s.eShip)>0
            		or
        		s.SortieEND<>'TKON'
                	or
                s.eAir>0
                	or
                s.addammo>0
                	or
                s.addfuel>0
                	or
                s.addrepair>0
                	or
                s.dfuel>0
                	or
                s.dammo>0
                	or
                s.drepair>0
            )
        		and
        	SortieEND != 'DIED'
        		and
        	SortieEND != 'MIA'
            	and
        	SortieEND != 'KICK'
            	and
        	SortieEND != 'DIEDISCO'
        	    and
			UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(s.starttime) < 14*24*60*60
        order by s.id DESC");

    echo mysql_error();

    $i = 0;
    $out['tkon'] = 0;

    while ($res = mysql_fetch_assoc($r)) {

    	$i = $i + $res['kills'] + $res['tanks'] +$res['gkills']/3 + ($res['dfuel'] + $res['dammo'] + $res['drepair'])/30;
    	$out['tkon'] ++;
    }

    $out['id']= $pilotid;
    $out['points'] = $i;

    return $out;

}


function GetSquadPoints ($squadid) {

    global $link;
    global $SERVER;

    $r = mysql_query("SELECT pilotid FROM finalpilots WHERE squadronid='$squadid'");

    $points = 0; $pilots_active = 0;
    while ($res = mysql_fetch_assoc($r)) {

    	$p = GetPilotPoints ($res['pilotid']);

    	$points = $points + $p['points'];

    	//echo "$p[points] <br>";
    	if ($p['points'] > 10)
    	//if ($p['tkon'] > 10)
    	  $pilots_active++;

    }

    $out['points'] = $points;
    $out['pilots_active'] = $pilots_active;

    return $out;
}


function GetSkladsReport () {

    global $link;
    global $SERVER;

    $r = mysql_query("SELECT
		  s.*,
		  SUM(m.tonnage) AS tonnage
		FROM
		  sklads_report s,  mission_objects m
		WHERE
		  (s.lid = m.lid) AND
		  (s.unit_class = m.unit_class)
		GROUP BY
		  m.lid, m.unit_class
		ORDER BY
		  armychar DESC, lid,
		  unit_class");

    $i = 0; $curr_lid = 0;

    while ($res = mysql_fetch_assoc($r)) {

       if ($res[lid] != $curr_lid) {
	       $i++;
	       $out[$i] = $res;
	       $curr_lid = $res[lid];

       }

       if ($res[unit_class] == 5) {
          $out[$i][ammo_back] = $res[ammo];
          $out[$i][ammo] = $res[tonnage];

       }
       else if ($res[unit_class] == 6) {

          $out[$i][fuel_back] = $res[fuel];
          $out[$i][fuel] = $res[tonnage];

       }
       else if ($res[unit_class] == 7) {

          $out[$i][repair_back] = $res[repair];
          $out[$i][repair] = $res[tonnage];

       }

    }

    return $out;
}

?>